<template>
<div class="ivu-table-wrapper">
<div class="ivu-table ivu-table-default ivu-table-stripe" ref="table">
<div class="ivu-table-header">
<table :style="{width: tableWidth}">
  <colgroup v-for="(item, index) in columns" :key="index" :width="getColWidth(item)">
  </colgroup>
  <thead>
    <th :class="'ivu-table-column-'+(item.align?item.align:'left')" v-for="(item, index) in columns" :key="index">
      <div v-if="item.type == 'selection'" class="ivu-table-cell ivu-table-cell-with-selection">
       <Checkbox v-model="allChecked"></Checkbox>
      </div>
      <div v-else class="ivu-table-cell">
      <span>{{item.title}}</span>
      </div>
    </th>
  </thead>
</table>
</div>
<div class="ivu-table-body">
<table :style="{width: tableWidth}">
  <colgroup v-for="(item, index) in columns" :key="index" :width="getColWidth(item)">
  </colgroup>
  <tbody>
    <tr :class="index%2 == 0? 'ivu-table-row': ''" v-if="item.level==1 || item.rowShow == true" v-for="(item, index) in tableData" :key="index" :width="getColWidth(item)">
      <td :class="'ivu-table-column-'+(itemm.align?itemm.align:'left')" v-for="(itemm, indexx) in columns" :key="indexx">
        <div v-if="itemm.type == 'selection'" class="ivu-table-cell ivu-table-cell-with-selection">
        <Checkbox @on-change="handleCheckboxChange" v-model='item.checked'></Checkbox>
        </div>
        <div v-else class="ivu-table-cell">
          <span :style="{'margin-left': 12*(item.level-1)+'px'}"></span>
          <Icon style="cursor:pointer;" @click="handleExpand(item)" v-if="itemm.tree && !item.leaf" :type="item.expand != true?'md-arrow-dropright':'md-arrow-dropdown'" size="18"/>
          <Cell v-if="itemm.render" :data="data" :column="itemm" :index="index"></Cell>
          <span v-else>{{item[itemm.key]}}</span>
        </div>
      </td>
    </tr>
  </tbody>
</table>
</div>
</div>
</div>
</template>
<script>
import Cell from './cell'
export default {
  components: {
    Cell
  },
  props: {
    data: {
      type: Array,
      default () {
        return []
      }
    },
    columns: {
      type: Array,
      default () {
        return []
      }
    },
    expandAll: {
      type: Boolean,
      default: false
    },
    expandLevel: {
      type: Number,
      default: 1
    }
  },
  data () {
    return {
      allChecked: false,
      selection: [],
      tableWidth: 0,
      cellWidth: 0,
      isFirst: true
    }
  },
  mounted () {
    this.resizeWidth()
    let $this = this
    window.onresize = function () {
      $this.resizeWidth()
    }
  },
  computed: {
    tableData () {
      if (this.isFirst) {
        if (this.expandAll) {
          this.data.forEach(item => {
            this.$set(item, 'rowShow', true)
            if (!item.leaf) {
              this.$set(item, 'expand', true)
            }
          })
        } else {
          this.data.forEach(item => {
            if (item.level <= this.expandLevel) {
              this.$set(item, 'rowShow', true)
            }
            if (item.level < this.expandLevel) {
              this.$set(item, 'expand', true)
            }
          })
        }
      }
      return this.data
    }
  },
  methods: {
    resizeWidth () {
      this.$nextTick(() => {
        this.tableWidth = window.getComputedStyle(this.$refs.table).width
        // this.tableWidth = parseInt(this.tableWidth) * 0.98 + 'px'
        let hasWidthColumns = this.hasWidthColumns()
        if (this.columns.length === hasWidthColumns.length) {
          this.cellWidth = 0
        } else {
          this.cellWidth = (parseInt(this.tableWidth) - this.hasWidthSum(hasWidthColumns)) / (this.columns.length - hasWidthColumns.length)
        }
      })
    },
    getColWidth (item) {
      if (item.width !== undefined) {
        return item.width
      } else {
        if (item.type === 'selection') {
          return 60
        }
        return this.cellWidth
      }
    },
    hasWidthColumns () {
      let columns = []
      this.columns.forEach((item, index) => {
        if (item.width !== undefined) {
          columns.push(item)
        } else {
          if (item.type === 'selection') {
            item.width = 60
            columns.push(item)
          }
        }
      })
      return columns
    },
    hasWidthSum (columns) {
      let sum = 0
      columns.forEach((item, index) => {
        if (item.width) {
          sum += item.width
        }
      })
      return sum
    },
    // 获取所有子元素
    getChildren (o) {
      var children = this.data.filter((item, index) => {
        return item.parentId === o.id
      })
      return children
    },
    // 获取所有可显示的子行
    getAllRowShowAble (o) {
      let result = []
      let children = this.getChildren(o)
      result.push(...children)
      if (children.length) {
        children.forEach((itemm, indexx) => {
          if (itemm.expand === true || itemm.rowShow === true) {
            result.push(...this.getAllRowShowAble(itemm))
          }
        })
      }
      return result
    },
    // 获取所有子元素，包含孙子
    getAllChildren (o) {
      let result = []
      let children = this.getChildren(o)
      result.push(...children)
      if (children.length) {
        children.forEach((itemm, indexx) => {
          result.push(...this.getAllChildren(itemm))
        })
      }
      return result
    },
    // 点击展开后事件
    handleExpand (e) {
      this.isFirst = false
      let children = []
      if (e.expand === true) {
        this.$set(e, 'expand', false)
        children = this.getAllChildren(e)
        children.forEach((item, index) => {
          this.$set(item, 'rowShow', false)
          // \\this.$set(item, 'expand', false)
        })
      } else {
        this.$set(e, 'expand', true)
        children = this.getAllRowShowAble(e)
        children.forEach((item, index) => {
          this.$set(item, 'rowShow', true)
        })
      }
    },
    handleCheckboxChange (arr) {
      this.$emit('on-selection-change', this.getSelection())
    },
    getSelection () {
      return this.data.filter((item, index) => {
        return item.checked === true
      })
    }
  },
  watch: {
    allChecked (n, o) {
      this.data.forEach((item, index) => {
        item.checked = n
      })
      this.$emit('on-selection-change', this.getSelection())
    }
  }
}
</script>
